#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>
/*
    int pthread_cond_init(pthread_cond_t * cond,
            const pthread_condattr_t * attr):
        初始化一个线程条件变量
        参数1：条件变量
        参数2：属性填NULL
    int pthread_cond_wait(pthread_cond_t*cond,
            pthread_mutex_t*mutex)
        等待一个条件变量，一旦被唤醒，该线程会进程运行态
        参数1：条件变量的地址
        参数2：线程互斥锁的地址，保证互斥锁是lock的状态
    int pthread_cond_signal(pthread_cond_t *cond)：
        唤醒等待条件变量的线程
        参数1：条件变量地址

*/
int data = 0;
struct type
{
    pthread_mutex_t* mutex;//互斥锁
    pthread_cond_t* cond;//条件变量
};

void* thread1_wakeuper(void* arg)
{
    struct type* p = (struct type*)arg;
    while (1)
    {
        pthread_mutex_lock(p->mutex);
        data++;
        if (data >= 100)
        {
            pthread_cond_signal(p->cond);//唤醒该事件的线程
        }
        pthread_mutex_unlock(p->mutex);
    }
}

void* thread2_sleeper(void* arg)
{
    struct type* p = (struct type*)arg;
    while (1)
    {
        pthread_mutex_lock(p->mutex);
        if (data < 100)
        {
            pthread_cond_wait(p->cond, p->mutex);
        }
        if (data >= 100)//处理数据
        {
            data = 0;
        }
        pthread_mutex_unlock(p->mutex);
    }
}

int main()
{
    struct type p;
    p.cond = malloc(sizeof(pthread_cond_t));
    p.mutex = malloc(sizeof(pthread_mutex_t));

    //初始化线程互斥锁和条件变量
    pthread_mutex_init(p.mutex, NULL);
    pthread_cond_init(p.cond, NULL);

    //创建两个线程
    pthread_t t1, t2;
    pthread_create(&t1, NULL, thread1_wakeuper, (void*)&p);//产生数据
    pthread_create(&t2, NULL, thread2_sleeper, (void*)&p);//等待产生

    while (1)
    {
        sleep(1);
        pthread_mutex_lock(p.mutex);
        printf("data:%d\n", data);
        pthread_mutex_unlock(p.mutex);
    }
}